<?php
namespace App\Action;
use App\Util\ActionMiddleware;
use App\Model\userModel;

class UserAction extends ActionMiddleware{
    
    public function index(){
        $model = new userModel();
        $data = $model->findAll();
        $this->display('user/index.html', array(
            'data'=>$data
        ));
    }
    
    
    public function view(){
        extract($this->input);
        $user_id = isset($user_id)?$user_id:0;
        $model = new userModel();
        $data = $model->find($user_id);
        $this->display('user/view.html', array(
            'data'=>$data
        ));
    }
    
    public function add(){
        extract($this->input);
        $username = isset($username)?$username:'';
        $password = isset($password)?$password:'';
        $age = isset($age)?$age:'';
        $address = isset($address)?$address:'';
        if($isPost){
            $model = new userModel();
            $data = array(
                'username'=>$username,
                'age'=>$age,
                'pwd'=>$password,
                'address'=>$address
            );
            $last_id = $model->add($data);
            if($last_id>0){
                $this->redirect('/user/index/');
            }
        }
        $this->display('user/add.html');
    }
    
    public function edit(){
        extract($this->input);
        $user_id = isset($user_id)?$user_id:0;
        $username = isset($username)?$username:'';
        $password = isset($pwd)?$pwd:'';
        $age = isset($age)?$age:'';
        $address = isset($address)?$address:'';
        
        $model = new userModel();
        if($isPost){
            $arr = array(
                'username'=>$username,
                'age'=>$age,
                'pwd'=>$password,
                'address'=>$address
            );
            $where = "where user_id='{$user_id}'";
            $re = $model->edit($arr, $where);
            if($re){
                $this->redirect('/user/index/');
            }
        }
        $data = $model->find($user_id);
        $this->display('user/edit.html',array(
            'data'=>$data,
        ));    
    }
    
    public function del(){
        extract($this->input);
        $user_id = isset($user_id)?$user_id:0;
        if($user_id>0){
           $model = new userModel();
           $where = "where user_id='{$user_id}'";
           $re = $model->del($where);
           if($re){
                $this->redirect('/user/index/');
           }
        }
    }
}
